<?php
/**
 * 大厅
 */
namespace app\socket;

use app\socket\Socket;
use think\facade\Cache;
use Workerman\Protocols\Websocket;
use app\service\User;
use app\service\Union;
use app\service\Table;
use app\handle\Table as hTable;

Class Hall extends Socket
{
    protected $socket = 'websocket://0.0.0.0:50000';

    // 枚举方法
    public $enumClassList = [
        'doClientProxy'         => [ 'args' => 3 ],
        'getClientProxyInfo'    => [ 'args' => 1 ],
        'heartBeat'             => [ 'args' => 1 ],
        'hello'                 => [ 'args' => 1 ],
        'login'                 => [ 'args' => 1 ],
        'getUserInfo'           => [ 'args' => 1 ],
        'getHallConfig'         => [ 'args' => 1 ],
        'getAllUnion'           => [ 'args' => 1 ],
        'switchTheUnion'        => [ 'args' => 2 ],
        'createUnion'           => [ 'args' => 2 ],
        'changeHeadimg'         => [ 'args' => 2 ],
        'getAllEmail'           => [ 'args' => 1 ],
        'getAllScore'           => [ 'args' => 1 ],
        'getScoreDetails'       => [ 'args' => 2 ],
        'deletedEmail'          => [ 'args' => 2 ],
        'readEmail'             => [ 'args' => 2 ],
        'createTable'           => [ 'args' => 2 ],
        'joinTable'             => [ 'args' => 2 ]
    ];

    public function __construct()
    {
        parent::__construct();
        $this->worker->count = 1;
    }

    // 客户端连接
    public function onConnect($conn)
    {
        // 设置连接类型
        $conn->websocketType = Websocket::BINARY_TYPE_ARRAYBUFFER;

        $this->cid = $conn->id;
        echo "客户端连接大厅id: ".$conn->id."\n";
        $this->sendDescribe($conn);
    }

    // 客户端关闭连接
    public function onClose($conn)
    {
        echo "客户端断开大厅连接id: ".$this->cid."\n";
    }

    public function hello($args)
    {
        return [
            '我们已经收到您的信息'
        ];
    }

    /**
     * 登录之后解析
     *
     * @param  [type] $args [description]
     * @return [type]       [description]
     */
    public function login($args, $conn)
    {
        if (empty($args) || empty($args[0])) {
            return $this->wsFailed('登录失败');
        }

        $uinfo = solveJwt($args[0]);
        if (empty($uinfo['id'])) {
            return $this->wsFailed('登录失败，数据解析错误');
        }

        // 获取信息
        $u_model = (new User())->u_model;
        (new User)->setOnline($uinfo['id'], $conn->id);
        $data = $u_model->where(['uid' => $uinfo['id']])->find();
        return $this->wsSuccess($data);
    }

    /**
     * 获取用户信息
     *
     * @param  [type] $args [description]
     * @return [type]       [description]
     */
    public function getUserInfo($args)
    {
        if (empty($args) || empty($args[0])) {
            return $this->wsFailed('登录失败');
        }

        $uinfo = solveJwt($args[0]);
        if (empty($uinfo['id'])) {
            return $this->wsFailed('登录失败，数据解析错误');
        }

        // 获取信息
        $u_model = (new User())->u_model;
        $data = $u_model->where(['uid' => $uinfo['id']])->find();
        return $this->wsSuccess($data);
    }

    /**
     * 获取大厅配置
     *
     * @param  [type] $args [description]
     * @return [type]       [description]
     */
    public function getHallConfig($args)
    {
        $getId = $this->tokenGetId($args[0]);
        if (empty($getId['uid'])) {
            return $getId;
        }

        $htable = new hTable(0, $getId['uid']);

        $result = [
            'notice' => '游戏仅供娱乐使用',
            'unreadEmail' => (new User)->getUnreadMsg($getId['uid']),
            'isGame' => $htable->playerHasATable()
        ];
        return $this->wsSuccess($result);
    }

    /**
     * 获取所有联盟
     *
     * @param  [type] $args [description]
     * @return [type]       [description]
     */
    public function getAllUnion($args)
    {
        $getId = $this->tokenGetId($args[0]);
        if (empty($getId['uid'])) {
            return $getId;
        }

        return $this->wsResult((new Union())->getRoomList($getId['uid']));
    }

    /**
     * 切换房间
     *
     * @param  [type] $args 0 => token 1 => 联盟id
     * @return [type]       [description]
     */
    public function switchTheUnion($args)
    {
        if (empty($args[1]) || $args[1] == 'undefined') {
            $list = $this->getAllUnion($args);
            if ($list['ok'] !== true) {
                return $this->wsFailed('获取桌子失败');
            }
            $array_list = json_decode($list['datas'], true);
            foreach ($array_list as $k => $v) {
                return $this->wsResult((new Table())->getTableByUnionId($v['rid']));
            }
        } else {
            return $this->wsResult((new Table())->getTableByUnionId($args[1]));
        }

        return $this->wsFailed('联盟不存在');
    }

    /**
     * 创建联盟
     *
     * @param  [type] $args 0 => token 1 => 联盟名称
     * @return [type]       [description]
     */
    public function createUnion($args)
    {
        $getId = $this->tokenGetId($args[0]);
        if (empty($getId['uid'])) {
            return $getId;
        }

        if (empty($args[1])) {
            return $this->wsFailed('请输入联盟名称');
        }

        $result = (new Union())->createRoom($getId['uid'], $args[1]);
        return $this->wsResult($result);
    }

    /**
     * 创建牌桌
     *
     * @param  [type] $arg 0 => token 1 => json字符串
     * @return [type]      [description]
     */
    public function createTable($args) {
        $getId = $this->tokenGetId($args[0]);
        if (empty($getId['uid'])) {
            return $getId;
        }
        $data = json_decode($args[1], true);
        $data['uid'] = $getId['uid'];

        return $this->wsResult((new Table())->createTable($data));
    }

    /**
     * 更换头像
     *
     * @param  [type] $args 0 => token 1 => 头像id
     * @return [type]       [description]
     */
    public function changeHeadimg($args)
    {
        $getId = $this->tokenGetId($args[0]);
        if (empty($getId['uid'])) {
            return $getId;
        }

        if ($args[1] === 0) {
            return $this->wsFailed('请选择需要更换的头像');
        }

        $u_model = (new User())->u_model;
        if ($u_model->save(['headimg' => $args[1]], ['uid' => $getId['uid']]) > 0) {
            return $this->wsSuccess([]);
        } else {
            return $this->wsFailed('头像更新失败');
        }
    }

    /**
     * 获取全部邮件
     *
     * @param  [type] $args [description]
     * @return [type]       [description]
     */
    public function getAllEmail($args)
    {
        $getId = $this->tokenGetId($args[0]);
        if (empty($getId['uid'])) {
            return $getId;
        }

        return $this->wsSuccess((new User)->getUserMsgList($getId['uid']));
    }

    /**
     * 获取全部战绩
     *
     * @param  [type] $args [description]
     * @return [type]       [description]
     */
    public function getAllScore($args)
    {
        $getId = $this->tokenGetId($args[0]);
        if (empty($getId['uid'])) {
            return $getId;
        }

        return $this->wsSuccess((new User)->getUserScoreList($getId['uid']));
    }

    /**
     * 获取战绩详细
     *
     * @param  [type] $args [description]
     * @return [type]       [description]
     */
    public function getScoreDetails($args)
    {
        return $this->wsSuccess((new User)->getScoreDetails($args[0], $args[1]));
    }

    /**
     * 删除邮件
     *
     * @param  [type] $args 0 => token 1 => id
     * @return [type]       [description]
     */
    public function deletedEmail($args)
    {
        $getId = $this->tokenGetId($args[0]);
        if (empty($getId['uid'])) {
            return $getId;
        }

        if ($args[1] === 0) {
            return $this->wsFailed('请选择需要删除的邮件');
        }

        (new User)->deletedUserEmail($getId['uid'], $args[1]);
        return $this->wsSuccess([]);
    }

    /**
     * 已读邮件
     *
     * @param  [type] $args 0 => token 1 => id
     * @return [type]       [description]
     */
    public function readEmail($args)
    {
        $getId = $this->tokenGetId($args[0]);
        if (empty($getId['uid'])) {
            return $getId;
        }

        (new User)->readUserEmail($getId['uid'], $args[1]);
        return $this->wsSuccess([]);
    }

    /**
     * 加入牌桌
     *
     * @param  [type] $args 0 => token 1 => tid(桌子id)
     * @return [type]       [description]
     */
    public function joinTable($args)
    {
        $getId = $this->tokenGetId($args[0]);
        if (empty($getId['uid'])) {
            return $getId;
        }

        $result = (new Table)->joinTableByTid($getId['uid'], $args[1]);
        return $this->wsResult($result);
    }

    // 心跳连接
    public function heartBeat($args, $conn)
    {
        $results = $this->tokenGetId($args[0]);
        if (empty($results['uid'])) {
            return $results;
        }

        $uService = new User;
        $online = $uService->getOnline($results['uid']);
        $uService->setOnline($results['uid'], $online);

        if ($conn->id != $online) {
            return [ 'ok' => true, 'code' => 4000, 'msg' => '您的账号已在其它地方登录' ];
        }

        return [ 'ok' => true, 'cid' => $conn->id, 'online' => $online ];
    }
}
